﻿namespace Calculator

open System.Windows.Controls
open System.Windows.Data
open System.Windows.Controls.Primitives
open System

open Wpf.Mvc

type MainWindowView() as this = 
    inherit View<MainWindowEvents, MainWindowModel, MainWindow>()

    let leftAndOperation : TextBox = this ? LeftAndOperation
    let input : TextBox = this ? Input
    let toggleWatch = this.Control.ToggleWatch

    override this.EventStreams = 
        let buttonClicks =
            [
                //digits
                this.Control.ZeroButton, Digit "0"
                this.Control.OneButton, Digit "1"
                this.Control.TwoButton, Digit "2"
                this.Control.ThreeButton, Digit "3"
                this.Control.FourButton, Digit "4"
                this.Control.FiveButton, Digit "5"
                this.Control.SixButton, Digit "6"
                this.Control.SevenButton, Digit "7"
                this.Control.EightButton, Digit "8"
                this.Control.NineButton, Digit "9"

                //ops
                this ? AddButton, Operation "+"
                this ? SubtractButton, Operation "-"
                this ? MultiplyButton, Operation "*"
                this ? DivideButton, Operation "/"

                //other
                this ? ClearButton, Clear
                this ? BackspaceButton, Backspace
                this ? ResultButton, CalculateResult

                this ? RestartWatch, RestartWatch

                this.Control.CelsiusToFahrenheit, CelsiusToFahrenheit
                this.Control.FahrenheitToCelsius, FahrenheitToCelsius
            ] 
            |> List.map(fun(button : Button, value) -> button.Click |> Observable.mapTo value)

        buttonClicks @ 
        [ 
            input.PreviewTextInput |> Observable.map (fun x -> InputChanging(x.Text, fun() -> x.Handled <- true))
            input.TextChanged |> Observable.mapTo InputChanged
            toggleWatch.Checked |> Observable.mapTo StopWatch
            toggleWatch.Unchecked |> Observable.mapTo StartWatch
        ] 

    override this.SetBindings model = 
        Binding.FromExpression 
            <@ 
                leftAndOperation.Text <- model.LeftAndOperator 
                toggleWatch.IsChecked <- model.Paused

                this.Control.RunningTime.Text <- String.Format("Running time: {0:hh\:mm\:ss}", model.RunningTime)

                this.Control.Celsius.Text <- string model.Celsius
                this.Control.Fahrenheit.Text <- string model.Fahrenheit
            @>

        Binding.UpdateSourceOnChange
            <@ input.Text <- model.Right @>


